var express = require('express');
var router = express.Router();
var { userModel, peoModel, emailModel } = require('../model/model')

//  邮箱功能
router.post('/myLogin', async (req, res) => {
  let { phone, password, isCode } = req.body;
  console.log(req.body)
  let user = await peoModel.find({ 'phone': phone, 'password': password })
  console.log(user)

  //  验证码验证
  let vaildCaptcha = await emailModel.findOneAndDelete({ 'phone': phone, 'code': isCode, 'expiresAt': { $gt: Date.now() }})
  console.log(vaildCaptcha)
  if(!user){
    res.send({
      code:500,
      msg:'账号或密码错误'
    })
  }else{
    if(!vaildCaptcha){
      res.send({
        code:500,
        msg:'验证码错误'
      })
    }else{
      res.send({
        code:200,
        msg:'登录成功',
        user
      })
    }
  }

})

//  邮箱登录功能

const sendEmail = require('../model/sendEmail')

let emailCode = (function captchaNumber() {
  let num = [];
  for (let i = 0; i < 6; i++) {
    num[i] = parseInt(Math.random() * 10);
  }
  return num.join('');
})()

//  验证码发送接口
router.post('/sendCode', async (req, res) => {
  console.log('你好')

  const { phone } = req.body;
  
  let user = await peoModel.findOne({ 'phone': phone });
  if (!user) {
    return res.send({
      code: 500,
      msg: '该用户不存在'
    })
  }
  let isCode = emailCode
  //  创建验证码记录
  let email = new emailModel({
    phone,
    code: isCode,
    expiresAt: Date.now() + 1000 * 60 //  1分钟后过期
  })

  let emaile = {
    title: '验证码',
    content: `您的验证码是${isCode}`
  }
  
  let emailContent = {
    from: 'songxiong101821ga@163.com', //  发送方的邮箱
    to: `${phone}`, //  接收方的邮箱
    subject: emaile.title,//  邮箱标题
    html: emaile.content//  邮箱内容
  };

  
  try {
    await email.save();
    //  发送邮箱验证码
    sendEmail.send(emailContent)
  } catch {
    console.log(err)
  }
})

module.exports = router;
